package com.gupao.core;

import com.gupao.config.JServletConfig;
import com.gupao.config.ServletConfigMapping;
import com.gupao.servlet.JemServlet;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Devin on 2018/1/9.
 * Tomcat窗口
 */
public class JTomcat {
    private int port =8080;

    public JTomcat() {
    }
    public JTomcat(int port) {
        this.port = port;
    }
    public void start() throws Exception {
        initServlets();
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("Tomcat start on "+this.port);
            while (true){
                Socket socket = serverSocket.accept();
                JRequest request = new JRequest(socket.getInputStream());
                JResponse response = new JResponse(socket.getOutputStream());
                dispatch(request,response);
//                String content =null;
//                byte[] buff = new byte[1024];
//                int len =0;
//                if ((len=socket.getInputStream().read(buff)) > 0){
//                    content = new String(buff,0,len);
//                }
//                System.out.println(content);

//                String resp = "HTTP/1.1 200 OK \n"+
//                        "Content-Type:text/html\n"+
//                        "\r\n"+
//                        "<html>"+
//                        "<body>Hello Tomcat</body>"+
//                        "</html>";
//                socket.getOutputStream().write(resp.getBytes());
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }

    }

    private Map<String,Class<JServlet>> servletMap = new HashMap<String, Class<JServlet>>();
    //初始化servlet
    private void initServlets() throws ClassNotFoundException {
        for (JServletConfig servletConfig: ServletConfigMapping.getConfigs()){
            servletMap.put(servletConfig.getUrlMapping(),(Class<JServlet>) Class.forName(servletConfig.getClazz()));
        }

    }

    //分发请求
    private void dispatch(JRequest request,JResponse response){
        Class<JServlet> clazz = servletMap.get(request.getUrl());
        try {
            if (null !=clazz){
                JServlet servlet = clazz.newInstance();
                servlet.service(request,response);
            }else {
                response.write("404 Not Found");
            }
        }catch (Exception e){
            response.write("500 Internal Error");
        }
    }


    public static void main(String[] args) throws Exception {
        new JTomcat().start();
    }

}
